import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:buy_flutter/net/net_utils.dart';
import 'package:buy_flutter/page/login/model/user.dart';
import 'package:equatable/equatable.dart';

part 'login_event.dart';

part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc() : super(LoginInitial("", "", User()));

  @override
  Stream<LoginState> mapEventToState(
    LoginEvent event,
  ) async* {
    print("mapEventToState=====>" + event.toString());
    if (event is LoginAccountChanged) {
      yield _mapUsernameChangedToState(event, state);
    } else if (event is LoginPasswordChanged) {
      yield _mapUserPswChangedToState(event, state);
    } else if (event is LogininChanged) {
      yield* _mapUserLoginChangedToState(event, state);
    }
  }

  LoginState _mapUsernameChangedToState(
      LoginAccountChanged event, LoginState state) {
    String userName = event.userName;
    return state.copyWith(account: userName);
  }

  LoginState _mapUserPswChangedToState(
      LoginPasswordChanged event, LoginState state) {
    String psw = event.password;
    return state.copyWith(psw: psw);
  }

  Stream<LoginState> _mapUserLoginChangedToState(
      LogininChanged event, LoginState state) async* {
    try {
      User user = await NetUtils.loginIn(acccount: "", password: "");
      yield state.copyWith(user: user);
    } on Exception catch (_) {
      yield state.copyWith();
    }
  }

}
